package com.livelab.java;

import com.livelab.model.Login;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

/**
 * Backing bean supporting "instructorForm" in "index.xhtml"
 * 
 * @author Dakota
 */
@ManagedBean(name = "instructorLoginBean")
@SessionScoped
public class InstructorLoginBean extends Login{
    
    private String courseId; //instructor's course id
    
    /**
     * Constructor
     */
    public InstructorLoginBean() {
        super();
    }

    @Override
    public void login() {
        try {
            //check for instructor with supplied username and password
            ResultSet rs = db.executeQuery("SELECT * FROM agsinstructor WHERE username = '" + getUsername() + "' AND password = '" + getPassword() + "';");
            FacesContext context = FacesContext.getCurrentInstance();

            //found
            if (rs != null && rs.next()) {
                setLoggedIn(true);
                courseId = rs.getString("courseId");
                context.addMessage(null, new FacesMessage("Logged In", "Instructor " + rs.getString("username")));
            }
            //not found
            else{
                 context.addMessage(null, new FacesMessage("Username/Password", "Invalid combination"));
                 setUsername("");
                 setPassword("");
            }
        } catch (SQLException ex) {
            Logger.getLogger(InstructorLoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Logs out Instructor
     */
    public void logout() {
        setLoggedIn(false);
        setUsername("");
        setPassword("");
    }

    /*
     * GETTERS
     */
    
    public String getCourseId() {
        return courseId;
    }
}
